package com.mimosa.util.extract;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;

/**
 * 基于正则表达式的规则抽取
 * 
 * @filename ExpressionExtractor.java
 * @datetime 2013年9月6日 下午5:23:55
 * @author ggeagle
 * 
 */
public class ExpressionExtractor extends Extractor {
	/**
	 * 规则的抽取正则表达式信息
	 */
	private List<Pattern> patternList = new ArrayList<Pattern>();

	@Override
	public Collection<ExtractHit> extract(String inputText) {
		Map<String, ExtractHit> result = new HashMap<String, ExtractHit>();
		if (this.patternList.size() > 0 && StringUtils.isNotBlank(inputText)) {
			for (Pattern pattern : this.patternList) {
				Matcher matcher = pattern.matcher(inputText);
				String value = null;
				ExtractHit extractHit = null;
				while (matcher.find()) {
					value = matcher.group();
					extractHit = result.get(value);
					if (extractHit == null) {
						extractHit = new ExtractHit();
						extractHit.setValue(value);
						result.put(value, extractHit);
					}
					extractHit.setCount(extractHit.getCount() + 1);
					extractHit.addIndexPoint(matcher.start());
				}
			}
		}
		return result.values();
	}

	@Override
	public void createByDicSettingEntity(Collection<String> entityList) {
		if (entityList != null && entityList.size() > 0) {
			Pattern pattern = null;
			for (String entity : entityList) {
				pattern = Pattern.compile(entity, Pattern.CASE_INSENSITIVE);
				this.patternList.add(pattern);
			}
		}
	}

	@Override
	public void clear() {
		this.patternList.clear();
	}
}